package com.javaweb.servlet;

import com.adminx.utils.ModelAndView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javaweb.vo.CommentVO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/test/ajax")
public class AjaxServlet extends HttpServlet {
    private Logger logger = LogManager.getLogger(NativeAjaxServlet.class) ;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
    }
    /**
     * override doPost logic from father by our own business logic
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getMethod() ;
        String action = null ;
        Map<String, Object> requestData = null ;
        if (type.equals("POST")) {
            requestData = getRequestData(req, Map.class) ;
            action = (String) requestData.get("action") ;
        } else {
            action = req.getParameter("action") ;
        }
        logger.debug("method: {}, action: {} ", type, action) ;
        switch (action) {
            case "register":
                doRegister(req, resp, requestData);
                break ;
            case "getComments":
                getComments(req, resp, requestData);
                break ;
            case "addComment":
                addComments(req, resp, requestData);
                break ;
            default:


        }



    }
    public void doRegister(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> requestData) throws ServletException, IOException {
        /**
         * process the arrived request in following logic.
         * At FIRST: SETTING ENCODING.
         */

        String userName = (String) requestData.get("name") ;
        String pwd =  (String) requestData.get("pwd") ;
        List<String> inst =  (List<String>) requestData.get("inst" ) ;
        logger.debug("do register for paramters (name, pwd, inst): {} {} {} ", userName, pwd, inst)  ;
        ModelAndView model = ModelAndView.buildSuccess(resp) ;
        model.addAttribute("result", "你获取了知识！") ;
        model.response();

    }

    public void getComments(HttpServletRequest req, HttpServletResponse resp,  Map<String, Object> requestData) throws ServletException, IOException {
        logger.debug("get comments")  ;
        ModelAndView model = ModelAndView.buildSuccess(resp) ;
        HttpSession session = req.getSession() ;
        if (session.getAttribute("commentList") == null) {
            session.setAttribute("commentList", CommentVO.generateComments());
        }
        model.addAttribute("comments", session.getAttribute("commentList")) ;
        model.response();
    }
    public void addComments(HttpServletRequest req, HttpServletResponse resp,  Map<String, Object> requestData) throws ServletException, IOException {
        logger.debug("recevied comment: {}", requestData.get("comment"))  ;
        ModelAndView model = ModelAndView.buildSuccess(resp) ;
        List<CommentVO> commentVOList = (List<CommentVO>) req.getSession().getAttribute("commentList") ;
        commentVOList.add(CommentVO.build(requestData)) ;
        model.response();
    }



    public String jsonString(HttpServletRequest request)throws IOException {

        // 先将 jsonString 读出来
        BufferedReader br = request.getReader();
        String line = null;
        StringBuilder jsonBuffer = new StringBuilder();
        while ((line = br.readLine()) != null) {
            jsonBuffer.append(line);
        }
        // 创建jsonObject

        return jsonBuffer.toString() ;


    }
    public static <T> T getRequestData(HttpServletRequest req, Class<T> clazz) {
        StringBuilder stringBuilder = new StringBuilder() ;
        ObjectMapper mapper = new ObjectMapper() ;
        String line = null ;
       try (BufferedReader reader = req.getReader()) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line) ;
            }
            return mapper.readValue(stringBuilder.toString(), clazz) ;
        } catch (Exception e) {
           e.printStackTrace();
       }
       return null ;
    }


}
